﻿
using System.Text.Json;

namespace fCloud.SensorApi.Services;

public interface ISseService { Task AddClient(HttpContext context); Task PushDataAsync<T>(T data); }
public class SseService : ISseService { private readonly List<HttpContext> _clients = new(); private readonly SemaphoreSlim _semaphore = new(1, 1);
    public async Task AddClient(HttpContext context)
    {
        await _semaphore.WaitAsync();
        try
        {
            _clients.Add(context);
            context.RequestAborted.WaitHandle.WaitOne();
        }
        finally
        {
            _clients.Remove(context);
            _semaphore.Release();
        }
    }

    public async Task PushDataAsync<T>(T data)
    {
        var json = JsonSerializer.Serialize(data);
        var sseMessage = $"data: {json}\n\n";

        await _semaphore.WaitAsync();
        try
        {
            foreach (var client in _clients.ToArray())
            {
                try
                {
                    await client.Response.WriteAsync(sseMessage);
                    await client.Response.Body.FlushAsync();
                }
                catch (Exception)
                {
                    _clients.Remove(client);
                }
            }
        }
        finally
        {
            _semaphore.Release();
        }
    }
}